package com.hazardSoft.eStore.bussines;

import java.util.List;

import javax.persistence.EntityManager;

import com.hazardSoft.eStore.common.exception.SystemException;
import com.hazardSoft.eStore.entities.Bill;
import com.hazardSoft.eStore.entities.Sale;
import com.hazardSoft.eStore.utils.PathConstants;

public class ShoppingCarBO {

	private static final String CLASS_NAME = PathConstants.BUSSINES_PATH+ShoppingCarBO.class.getSimpleName();
	private List<Sale> sales;
	
	public ShoppingCarBO(List<Sale> sales) {
		this.sales = sales;
	}


	public void addProduct(Sale sale) throws SystemException {
		if (sales.contains(sale)) {
			for (Sale tempSale : sales) {
				if (sale.equals(tempSale)) {
					tempSale.setQuantity(tempSale.getQuantity()+sale.getQuantity());
					tempSale.setCost(tempSale.getQuantity()*tempSale.getProduct().getCost());
				}
			}
		} else {
			sale.setCost(sale.getQuantity()*sale.getProduct().getCost());
			sales.add(sale);
		}
	}

	
	public Bill buyProducts(Bill bill, EntityManager entityManager) throws SystemException {
		if (bill == null) {
			throw new SystemException(new Exception("null bill"), CLASS_NAME, "buyProducts");
		}
		BillsBO billsBO = new BillsBO();
		bill.setSaleCollection(sales);
		
		bill = billsBO.insertBil(bill, entityManager);
		
		sales.clear();
		
		return bill;
	}

	
	public List<Sale> listProducts() throws SystemException {
		
		return sales;
	}

	
	public void removeProduct(Sale sale) throws SystemException {
		
		sales.remove(sale);
	}

	
	public void setProducts(List<Sale> sales) throws SystemException {
	
		this.sales = sales;
	}

}
